<template>
  <div class="editWedding">
    <h1 v-if="id">编辑婚礼案例</h1>
    <h1 v-else>添加婚礼案例</h1>

    <el-form class="box" :model="ruleForm" ref="ruleForm" :rules="rules" label-width="80px">
      <el-form-item label="轮播图:" prop="imagesData">
        <template slot-scope="scope">
          <form class="banner_loade" enctype="multipart/form-data">
            <el-button class="upload" type="primary ">
              添加多张图片
              <input class="file" type="file" name="file" @change="uploadImg($event)" />
            </el-button>

            <div class="loade_img" :class="{hide:ruleForm.imagesData!=''}">
              <div style="position: relative;" v-for="(img,index) in ruleForm.imagesData" :key="index">
                <img class="img_auto" :src="img" alt />
                <i class="el-icon-error icon" @click="deleteImg(index)"></i>
              </div>
            </div>
          </form>
        </template>
      </el-form-item>


      <el-form-item label="案例名:" label-width="120px" prop="casename">
        <el-input v-model.trim="ruleForm.casename"></el-input>
      </el-form-item>
      <el-form-item label="标签:" label-width="120px" prop="dynamicTags">
        <el-tag :key="tag" v-for="(tag,index) in ruleForm.dynamicTags" closable :disable-transitions="false" @close="handleClose(index)">{{tag}}</el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
          @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"></el-input>
        <el-button class="button-new-tag" size="small" v-if="show" @click="showInput()">+ New Tag</el-button>
      </el-form-item>
      <el-form-item label="酒店:" label-width="120px" prop="address">
        <el-input v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="拍摄/婚礼日期:" label-width="120px" prop="photoTime">
        <el-date-picker v-model="ruleForm.photoTime" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>

      <el-form-item label="单价:" label-width="120px" prop="price">
        <el-input v-model="ruleForm.price"></el-input>
      </el-form-item>
      <el-form-item label="图文介绍:" class="edit" label-width="120px">
        <div id="editorElem" style="width:55vw"></div>
      </el-form-item>

      <el-form-item>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveInfo(ruleForm)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import E from "wangeditor";
  import $ from "jquery";
  import Qiniu from "../../../static/js/qiniu";
  export default {
    data() {
      return {
        editorContent: "", //富文本

        ruleForm: {
          casename: "", //案例名称
          address: "", //地址
          photoTime: "", //拍摄时间
          price: "", //价格
          dynamicTags: [], //标签
          imagesData: [], //轮播图片
        },

        inputVisible: false,
        inputValue: "",
        show: true,
        id: "",
        rules: {
          casename: [{
            required: true,
            message: '案例名称不能为空',
            trigger: 'blur'
          }],
          address: [{
            required: true,
            message: '酒店名称不能为空',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '价格不能为空',
            trigger: 'blur'
          }],
          photoTime: [{
            required: true,
            message: '拍摄日期不能为空',
            trigger: 'blur'
          }],
          dynamicTags: [{
            required: true,
            message: '标签不能为空',
            trigger: 'blur'
          }],
          imagesData: [{
            required: true,
            message: '轮播图不能为空',
            trigger: 'blur'
          }],
        }
      }
    },
    created() {
      setTimeout(() => {
        this.wangeditor();
      }, 1000)
      let id = this.$route.query.infoId;
      this.id = this.$route.query.infoId;
      console.log(id);
      if (id) {
        //值不存在
        //值存在请求接口
        this.api
          .get("/api/wedding", {
            id: id
          })
          .then(res => {
            console.log(res.data);
            let info = res.data;
            this.ruleForm.imagesData = info.rotation;
            this.ruleForm.dynamicTags = info.lable;
            this.ruleForm.price = info.price;
            this.ruleForm.address = info.position;
            this.ruleForm.photoTime = info.weddingday;
            this.ruleForm.casename = info.title;
            this.editorContent = info.images;
          });
      }
    },
    methods: {
      wangeditor() {
        var editor = new E("#editorElem");
        editor.customConfig.onchange = html => {
          this.editorContent = html;
        };
        editor.customConfig.qiniu = true;
        editor.customConfig.pasteFilterStyle = false;
        editor.create();
        editor.txt.html(this.editorContent);
        this.uploaderInit(editor);
      },
      blobToFile(dataurl, filename) { //base64位图片 转图片文件
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },
      imgPreview(file, dataInfo) {
        let self = this
        // 判断是否支持FileReade
        if (!file || !window.FileReader) return
        // 创建一个reader
        var reader = new FileReader()
        // 将图片转成base64格式
        reader.readAsDataURL(file)
        // 读取成功后的回调
        reader.onloadend = function() {
          let result = this.result
          let img = new Image()
          img.src = result
          console.log('============未压缩图片===========')
          console.log(result.length)
          img.onload = function() {
            let data = self.compress(img)
            console.log(data.length)
            self.imgUrl = result
            var param = new FormData()
            let imgData = self.blobToFile(data, 'ig1')
            console.log(data)
            param.append('files', imgData)
            self.api.post('/api/imgs', param).then(res => {
              dataInfo.push(res.data[0])
            })
          }
        }
      },
      compress(img) {
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        let initSize = img.src.length;
        let width = img.width;
        let height = img.height;
        canvas.width = width;
        canvas.height = height;
        // 铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, width, height);

        //进行最小压缩
        let ndata = canvas.toDataURL("image/jpeg", 0.1);
        console.log("*******压缩后的图片大小*******");
        // console.log(ndata)
        console.log(ndata.length);
        return ndata;
      },
      uploadImg(e) {
        let that = this;
        let formData = new FormData()
        let reader = new FileReader()
        let imgName = e.target.files[0]
        reader.readAsDataURL(e.target.files[0])
        that.imgPreview(imgName, that.ruleForm.imagesData)
        // //上传图片
        // console.log(e);
        // let file = e.target.files[0];
        // let param = new FormData();
        // param.append("files", file, file.name);
        // let config = {
        //   headers: {
        //     "Content-Type": "multipart/form-data"
        //   }
        // };
        // this.api.post("/api/imgs", param, config).then(res => {
        //   this.formline.imagesData.push(res.data[0]);
        // });


      },

      wedd() {
        this.api.get("/api/lookcompany").then(res => {
          console.log(res);
          alert(res);
        });
      },
      handleClose(index) {
        //删除标签
        this.ruleForm.dynamicTags.splice(index, 1);
        if (this.ruleForm.dynamicTags.length != 3) {
          this.show = true;
        }
      },
      showInput() {
        //添加标签
        if (this.ruleForm.dynamicTags.length >= 3) {
          this.show = false;
          alert("标签最多添加三个");
        } else {
          this.inputVisible = true;
          this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
          });
        }
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.ruleForm.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = "";
      },
      saveInfo(ruleForm) {
        this.$refs.ruleForm.validate((valid) => {
          const _this = this;
          if (valid) {
            var param = {
              lable: _this.ruleForm.dynamicTags,
              rotation: _this.ruleForm.imagesData,
              position: _this.ruleForm.address,
              price: _this.ruleForm.price,
              title: _this.ruleForm.casename,
              weddingday: _this.ruleForm.photoTime,
              images: _this.editorContent
            };
            if (this.id) {
              //编辑
              _this.$set(param, 'id', _this.id);
              console.log(param)
              _this.api.post("/api/editwedding", param).then(res => {
                console.log(res.data)
                if (res.data) {
                  let info = res.data;
                  _this.ruleForm.imagesData = JSON.parse(info.rotation);
                  _this.ruleForm.dynamicTags = JSON.parse(info.lable);
                  _this.ruleForm.price = info.price;
                  _this.ruleForm.address = info.position;
                  _this.ruleForm.photoTime = info.weddingday;
                  _this.ruleForm.casename = info.title;
                  _this.editorContent = info.images;
                  _this.$message({
                    type: 'success',
                    message: '保存成功！'
                  })
                  setTimeout(function() {
                    _this.$router.go(-1);
                  }, 3000);
                }
              });
            } else {
              //添加
              console.log(_this.editorContent)
              _this.api.post("/api/addwedding", param).then(res => {
                console.log(res.data);
                if (res.data) {
                  let info = res.data;
                  _this.ruleForm.imagesData = JSON.parse(info.rotation);
                  _this.ruleForm.dynamicTags = JSON.parse(info.lable);
                  _this.ruleForm.price = info.price;
                  _this.ruleForm.address = info.position;
                  _this.ruleForm.photoTime = info.weddingday;
                  _this.ruleForm.casename = info.title;
                  _this.imgintro = info.images;
                  _this.$message({
                    type: 'success',
                    message: '保存成功！'
                  })
                  setTimeout(function() {
                    _this.$router.go(-1);
                  }, 3000);

                }
              });
            }
          } else {
            _this.$message({
              type: 'warning',
              message: '请将字段填写完整!'
            })
            return false;
          }
        });

      },
      deleteImg(index) {
        //删除图片
        this.ruleForm.imagesData.splice(index, 1);
        this.$message({
          type: 'info',
          message: '删除成功！'
        })
      },
      cancel() {
        this.$router.go(-1)
      },
      // 富文本
      uploaderInit(editor) {
        var that = this;
        var btnId = editor.imgMenuId;
        var containerId = editor.toolbarElemId;
        var textElemId = editor.textElemId;
        that.api.post("/api/uptoken", {}).then(res => {
          var uploader = new Qiniu().uploader({
            runtimes: "html5,flash,html4", //上传模式,依次退化
            browse_button: btnId, //上传选择的点选按钮，**必需**
            uptoken: res.data,
            unique_names: true,
            save_key: true,
            domain: "http://vrqn.liuliangin.com/", //bucket 域名，下载资源时用到，**必需**
            container: containerId, //上传区域DOM ID，默认是browser_button的父元素，
            max_file_size: "100mb", //最大文件体积限制
            filters: {
              mime_types: [
                //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
                {
                  title: "图片文件",
                  extensions: "jpg,gif,png,bmp"
                }
              ]
            },
            max_retries: 3, //上传失败最大重试次数
            dragdrop: true, //开启可拖曳上传
            drop_element: textElemId, //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
            chunk_size: "4mb", //分块上传时，每片的体积
            auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
            init: {
              FilesAdded: function(up, files) {
                plupload.each(files, function(file) {
                  // 文件添加进队列后,处理相关的事情
                  that.printLog("on FilesAdded");
                });
              },
              BeforeUpload: function(up, file) {
                // 每个文件上传前,处理相关的事情
                that.printLog("on BeforeUpload");
              },
              UploadProgress: function(up, file) {
                // 显示进度
                that.printLog("进度 " + file.percent);
              },
              FileUploaded: function(up, file, info) {
                // 每个文件上传成功后,处理相关的事情
                // 其中 info 是文件上传成功后，服务端返回的json，形式如
                // {
                //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //    "key": "gogopher.jpg"
                //  }
                that.printLog(info);
                // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
                var domain = up.getOption("domain");
                var res = $.parseJSON(info.response);
                var sourceLink = domain + res.key; //获取上传成功后的文件的Url
                that.printLog(sourceLink);
                // 插入图片到editor
                editor.cmd.do(
                  "insertHtml",
                  '<img src="' + sourceLink + '" style="max-width:100%;"/>'
                );
              },
              Error: function(up, err, errTip) {
                //上传出错时,处理相关的事情
                that.printLog("on Error");
              },
              UploadComplete: function() {
                //队列文件处理完毕后,处理相关的事情
                that.printLog("on UploadComplete");
              }
            }
            //upload的括号
          });
        });
      },
      printLog(title, info) {
        console.log(title, "1");
        console.log(info, "2");
        window.console && console.log(title, info);
      }
      // 富文本结束
    }
  };
</script>

<style scoped>
  .box {
    width: 50%;
  }

  .file {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 35px;
    line-height: 35px;
    text-align: center;
    opacity: 0;
  }

  .el-button {
    width: 100px;
  }

  .loade_img {
    background: url("./../../../static/img/push.jpg") no-repeat;
    background-size: 80px 80px;
    width: 100%;
    height: 80px;
    margin: 5px;
  }

  .loade_img div {
    margin: 5px;
    width: 80px;
    float: left;
  }

  .loade_img img {
    width: 80px;
  }

  .hide {
    background-image: none;
  }

  .img_auto {
    position: relative;
   max-width: 100%;
   width: 100%;
   max-height: 100%;
   height: 100%;
   object-fit: cover;
  }

  .icon {
    font-size: 25px;
    position: absolute;
    top: -8px;
    right: -8px;
  }

  .upload {
    position: relative;
    width: 120px;
    height: 35px;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .edit>>>.el-form-item__content {
    z-index: 1;
  }
</style>
